package com.books.service.impl;

import com.books.entity.EbookEntry;
import com.books.mapper.EbookEntryMapper;
import com.books.service.EbookEntryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cd
 * @version 1.0
 * @date 2021/10/6 12:26
 */
@Service
public class EbookEntryServiceImpl implements EbookEntryService {

    @Autowired
    private EbookEntryMapper ebookEntryMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insert(EbookEntry ebookEntry) {
        int i = ebookEntryMapper.insert(ebookEntry);
        if (i != 1) {
            System.out.println("添加图书失败");
            throw new RuntimeException("添加图书失败");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateById(EbookEntry ebookEntry) {
        int i = ebookEntryMapper.updateByPrimaryKeySelective(ebookEntry);
        if (i != 1) {
            System.out.println("修改图书失败");
            throw new RuntimeException("修改图书失败");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteById(Integer id) {
        int i = ebookEntryMapper.deleteByPrimaryKey(id);
        if (i != 1) {
            System.out.println("删除图书失败");
            throw new RuntimeException("删除图书失败");
        }
    }

    @Override
    public EbookEntry findById(Integer id) {
        return ebookEntryMapper.findById(id);
    }

    @Override
    public PageInfo<EbookEntry> findByEntryIdAndPage(Integer page, Integer rows, Integer categoryId) {
        //1. 分页
        PageHelper.startPage(page,rows);

        //2. 查询
        List<EbookEntry> ebookList = ebookEntryMapper.findByEntryId(categoryId);

        //3. 封装PageInfo
        PageInfo<EbookEntry> pageInfo = new PageInfo<>(ebookList);

        //4. 返回
        return pageInfo;
    }
}
